import urllib,urllib2,re,sys,xbmcplugin,xbmcgui
import cookielib,os,string,cookielib,StringIO
import os,time,base64,logging,calendar
import xbmcaddon
from xml.dom.minidom import parse, parseString

#IPL Twenty20
wtv=xbmcaddon.Addon(id='plugin.video.iplt20')

addonPath=os.getcwd()
artPath=addonPath+'/resources/art'
artPathIPL2011=artPath+'/2011'
defaultIconImg=os.path.join(xbmc.translatePath( artPath ), "cricket-icon.png")


def HOME():
        xbmc.executebuiltin("XBMC.Notification(IPL 2011 is here,ENJOY your time with LIVE streaming,5000,)")
        iconImg=os.path.join(xbmc.translatePath( artPath ), "cricket-icon.png")
        fanart=os.path.join(xbmc.translatePath( artPathIPL2011 ), "teams-logo.jpg")
        addDir("[B]CURRENT MATCH[/B] (Indiatimes)","http://ipl.indiatimes.com/",1,iconImg,fanart)
        addDir("[B]ABSOLUTELY LIVE MATCH[/B] (SET MAX)","LOW",4,iconImg,fanart)
        retrievePlaylists()
        
        
def LIVE(url,name):
        try:
                
                req = urllib2.Request(url)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                response = urllib2.urlopen(req)
                link=response.read()
                response.close()
                link=''.join(link.splitlines()).replace('\t','')
                configLink=re.compile('var TMConfigURL="(.+?)";').findall(link)
                print "CONFIG LINK ="+ configLink[0]
                confighdLink=re.compile('var TMConfigAkhdURL="(.+?)";').findall(link)
                print "HD CONFIG LINK ="+ confighdLink[0]
                try:
                        retrieveCurrentMatchLinks(configLink[0])
                except: pass
                
                try:
                        retrieveCurrentMatchLinks(confighdLink[0])
                except: pass

        except:
                pass
                d = xbmcgui.Dialog()
                d.ok('NO CURRENT MATCH FOUND', 'No LIVE or CURRENT match is available yet. BREAK TIME!','Please come back again after some time.')
                return False
        
        
def retrieveCurrentMatchLinks(url):

                iconImg=os.path.join(xbmc.translatePath( artPath ), "cricket-icon.png")
                fanart=os.path.join(xbmc.translatePath( artPathIPL2011 ), "teams-logo.jpg")
                req = urllib2.Request(url)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                response = urllib2.urlopen(req)
                link=response.read()
                response.close()
                link=''.join(link.splitlines())
                domObj = parseString(link)
                streamXmlLink=getText(domObj.getElementsByTagName("streamProperties")[0].childNodes)
        
                print "Streaming XML Link = "+streamXmlLink
                url=streamXmlLink
                req = urllib2.Request(url)
                req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
                response = urllib2.urlopen(req)
                link=response.read()
                response.close()
                link=''.join(link.splitlines())
                domObj = parseString(link)
                streamsInfo=domObj.getElementsByTagName("streamInfo")
                for streamInfo in streamsInfo:
                        streamName = getText(streamInfo.getElementsByTagName("streamName")[0].childNodes)
                        print streamName
                        #streamName = "IPL 2011 LIVE CRICKET match about to start or already started"
                        addDir(streamName,streamInfo.toxml("utf-8"),20,iconImg,fanart)
                        

def LIVEVIDEOLINKS(url,name):
        iconImg=os.path.join(xbmc.translatePath( artPath ), "playnow_icon.png")
        fanart=os.path.join(xbmc.translatePath( artPathIPL2011 ), "teams-logo.jpg")
        
        
        streamInfo = parseString(url)
        sources=streamInfo.getElementsByTagName("source")
        linkNbr = 0
        for source in sources:
                liveServerUrl = "rtmp://" + getText(source.childNodes).replace("/",":1935/") + " live=true app=live swfVfy=true swfUrl=http://livepassdl.conviva.com/ver/2.24.0.41237/LivePassModuleMain.swf pageUrl=http://us.ipl.indiatimes.com// "
                linkNbr = linkNbr + 1
                
                bitrates=streamInfo.getElementsByTagName("bitrate")
                for bitrate in bitrates:
                        qualityrate = bitrate.getAttribute("rate") 
                        playpath = bitrate.getAttribute("urlSuffix")
                        
                        liveLink = liveServerUrl + " playpath=" + playpath
                        liveLinkName = "LIVE STREAMING SERVER "+str(linkNbr)+" with QUALITY RATE = "+qualityrate 
                        print "LiveStreaming Link = "+liveLink
                        addLink(liveLinkName,liveLink,iconImg)
        xbmc.executebuiltin("XBMC.Notification(HIGHEST QUALITY RATE,For high quality video. select link with highest Quality Rate,5000,)")
        

def AbsoluteLive(url,name):
        iconImg=os.path.join(xbmc.translatePath( artPath ), "playnow_icon.png")
        addLink('LOW QUALITY STREAM LINK - 1','rtmp://50.23.239.59/liveorigin/_definst_/108149 swfVfy=true swfUrl=http://lankajustin.tv/player/player.swf  live=true pageUrl=http://lankajustin.tv/player.php?channel_id=108149&width=600&height=430',iconImg)
        addLink('LOW QUALITY STREAM LINK - 2','rtmp://46.182.123.28/live app=live swfVfy=true swfUrl=http://icctv.info/star.swf  live=true playpath=ipl pageUrl=http://cricfree.in/tv.php',iconImg)
        addLink('LOW QUALITY STREAM LINK - 3','rtmp://mipscdn.tv:1935/live/_definst_/ipladsfasd54a',iconImg)


def getPlaylistTitle(playlist):
        return getText(playlist.getElementsByTagName("title")[0].childNodes)
        
def getPlaylistID(playlist):
        return getText(playlist.getElementsByTagName("yt:playlistId")[0].childNodes)
        
def getPlaylistUpdatedDT(playlist):
        return getText(playlist.getElementsByTagName("updated")[0].childNodes)
        
        
def retrievePlaylists():
        url='http://gdata.youtube.com/feeds/api/users/indiatimes/playlists?v=2'
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        domObj = parseString(link)
        #print domObj.toprettyxml()
        playlists=domObj.getElementsByTagName("entry")
        for playlist in playlists:
                playListTitle = getPlaylistTitle(playlist)
                print 'playListTitle = '+playListTitle
                
                playlistID = getPlaylistID(playlist)
                print 'playListID = '+playlistID
                
                lastUpdatedTime = getPlaylistUpdatedDT(playlist)
                print 'lastUpdatedTime = '+lastUpdatedTime
                
                datetime_obj = time.strptime(lastUpdatedTime, '%Y-%m-%dT%H:%M:%S.000Z')
                localUpdatedDate = time.strftime('%a, %b %d %I:%M %p', time.localtime(calendar.timegm(datetime_obj)))
                print "lastUpdated DATETIME = "+localUpdatedDate
                
                url='http://gdata.youtube.com/feeds/api/playlists/'+playlistID+'?v=2'
                if(len(playListTitle) == 0):
                        playListTitle = 'Face-off'
                addDir('[B]'+playListTitle + '[/B] (Last Updated: '+localUpdatedDate+')',url,2,'','')
                

        
def PlaylistVideos(url,name):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        domObj = parseString(link)
        #print domObj.toprettyxml()
        videos=domObj.getElementsByTagName("entry")
        retrieveVideos(videos)
        if(len(videos) == 0):
                d = xbmcgui.Dialog()
                d.ok('NO VIDEOS FOUND', 'There are no videos posted under this category','Check later.')
                

        
def getVideoTitle(video):
        return getText(video.getElementsByTagName("title")[0].childNodes)
        
def getVideoID(video):
        return getText(video.getElementsByTagName("yt:videoid")[0].childNodes)
        
        

def retrieveVideos(videos):
        for video in videos:
                videoTitle = getVideoTitle(video)
                print '\tvideoTitle = '+videoTitle
                videoID = getVideoID(video)
                print '\tvideoID = '+videoID
                addDir(videoTitle,videoID,3,'http://i.ytimg.com/vi/'+videoID+'/default.jpg','')
                
                
def VideoLinks(url,name):
        linkImage = 'http://i.ytimg.com/vi/'+url+'/default.jpg'
        req = urllib2.Request('http://www.youtube.com/watch?v='+url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        p=re.compile(';fmt_url_map=(.+?);')
        match=p.findall(link)
        map=match[0].split('%2C')
        highResoVid = ''
        for attr in map:
                parts = attr.split('%7C')
                qual = parts[0]
                url = urllib.unquote(parts[1]).decode('utf8')
                if(qual == '13'):
                        addLink ('PLAY Low Quality - 176x144',url+'#t=01h31m31s',linkImage)
                
                if(qual == '17'):
                        addLink ('PLAY Medium Quality - 176x144',url+'#t=01h31m31s',linkImage)
                        
                if(qual == '36'):
                        addLink ('PLAY High Quality - 320x240',url+'#t=01h31m31s',linkImage)
                        
                if(qual == '5'):
                        addLink ('PLAY Low Quality - 400\\327226',url+'#t=01h31m31s',linkImage)
                        
                if(qual == '34'):
                        addLink ('PLAY Medium Quality - 480x360',url+'#t=01h31m31s',linkImage)
                        
                if(qual == '6'):
                        addLink ('PLAY Medium Quality - 640\\327360',url+'#t=01h31m31s',linkImage)
                        
                if(qual == '35'):
                        addLink ('PLAY High Quality - 854\\327480',url+'#t=01h31m31s',linkImage)
                        
                if(qual == '18'):
                        addLink ('PLAY High Quality - 480x360',url+'#t=01h31m31s',linkImage)
                                        
                if(qual == '22'):
                        addLink ('PLAY High Quality - 1280x720',url+'#t=01h31m31s',linkImage)
                                
                if(qual == '37'):
                        addLink ('PLAY High Quality - 1920x1080',url+'#t=01h31m31s',linkImage)
                                
                if(qual == '38'):
                        addLink ('PLAY Epic Quality - 4096\\3272304',url+'#t=01h31m31s',linkImage)
                                
        
def addLink(name,url,iconimage):
        if(iconimage == ''):
                iconimage = defaultIconImg
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        fanart=os.path.join(xbmc.translatePath( artPathIPL2011 ), "teams-logo.jpg")
        liz.setProperty('fanart_image',fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok


def addDir(name,url,mode,iconimage,fanart):
        if(iconimage == ''):
                iconimage = defaultIconImg
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        if(fanart==''):
                fanart=os.path.join(xbmc.translatePath( artPathIPL2011 ), "teams-logo.jpg")
        liz.setProperty('fanart_image',fanart)
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

        
        
def getText(nodelist):
        rc = []
        for node in nodelist:
                if node.nodeType == node.TEXT_NODE:
                        rc.append(node.data)
        return ''.join(rc)




def unescape(url):
        htmlCodes = [
                ['&', '&amp;'],
                ['<', '&lt;'],
                ['>', '&gt;'],
                ['"', '&quot;'],
        ]
        for code in htmlCodes:
                url = url.replace(code[1], code[0])
        return url

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

params=get_params()
url=None
name=None
option=None
mode=None


try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        option=params["option"]
except:
        pass

if mode==None or url==None or len(url)<1:
        HOME()

elif mode==1:
        LIVE(url,name)

elif mode==2:
        PlaylistVideos(url,name)

elif mode==3:
        VideoLinks(url,name)

elif mode==4:
        AbsoluteLive(url,name)

elif mode==20:
        LIVEVIDEOLINKS(url,name)
     
xbmcplugin.endOfDirectory(int(sys.argv[1]))
